import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 应用设置状态管理Provider
/// 管理主题、用户偏好、通知设置等
class SettingsProvider with ChangeNotifier {
  static const String _themeKey = 'theme_mode';
  static const String _languageKey = 'language';
  static const String _notificationKey = 'notification_enabled';
  static const String _reminderTimeKey = 'reminder_time';
  static const String _privacyModeKey = 'privacy_mode';
  static const String _autoBackupKey = 'auto_backup';
  static const String _firstLaunchKey = 'first_launch';
  static const String _appLockKey = 'app_lock_enabled';
  static const String _analyticsKey = 'analytics_enabled';

  SharedPreferences? _prefs;
  
  // 主题设置
  ThemeMode _themeMode = ThemeMode.system;
  
  // 语言设置
  Locale _locale = const Locale('zh', 'CN');
  
  // 通知设置
  bool _notificationEnabled = true;
  bool _dailyReminderEnabled = true;
  TimeOfDay _reminderTime = const TimeOfDay(hour: 20, minute: 0);
  
  // 字体设置
  double _fontSize = 16.0;
  
  // 主题颜色设置
  Color _primaryColor = Colors.blue;
  
  // 隐私设置
  bool _privacyMode = false;
  
  // 备份设置
  bool _autoBackup = true;
  
  // 分析统计设置
  bool _analyticsEnabled = true;
  
  // 应用锁设置
  bool _appLockEnabled = false;
  
  // 应用状态
  bool _isFirstLaunch = true;
  bool _isInitialized = false;

  /// 构造函数
  SettingsProvider() {
    _initialize();
  }
  
  /// 公共初始化方法
  Future<void> initialize() async {
    await _initialize();
  }

  // Getters
  ThemeMode get themeMode => _themeMode;
  Locale get locale => _locale;
  bool get notificationEnabled => _notificationEnabled;
  bool get notificationsEnabled => _notificationEnabled;
  bool get dailyReminderEnabled => _dailyReminderEnabled;
  TimeOfDay get reminderTime => _reminderTime;
  double get fontSize => _fontSize;
  Color get primaryColor => _primaryColor;
  bool get privacyMode => _privacyMode;
  bool get autoBackup => _autoBackup;
  bool get analyticsEnabled => _analyticsEnabled;
  bool get appLockEnabled => _appLockEnabled;
  bool get isFirstLaunch => _isFirstLaunch;
  bool get isInitialized => _isInitialized;
  
  /// 是否为深色主题
  bool get isDarkMode => _themeMode == ThemeMode.dark;
  
  /// 是否为系统主题
  bool get isSystemTheme => _themeMode == ThemeMode.system;
  
  /// 是否为中文
  bool get isChinese => _locale.languageCode == 'zh';
  
  /// 获取语言代码
  String get languageCode => _locale.languageCode;
  
  /// 获取主题模式字符串
  String get themeModeString {
    switch (_themeMode) {
      case ThemeMode.light:
        return 'light';
      case ThemeMode.dark:
        return 'dark';
      case ThemeMode.system:
// 已经覆盖所有ThemeMode枚举值,无需default分支
        return 'system';
    }
  }

  /// 初始化设置
  Future<void> _initialize() async {
    try {
      _prefs = await SharedPreferences.getInstance();
      await _loadSettings();
      _isInitialized = true;
      notifyListeners();
    } catch (e) {
      if (kDebugMode) {
        print('初始化设置失败: $e');
      }
    }
  }

  /// 加载所有设置
  Future<void> _loadSettings() async {
    if (_prefs == null) return;
    
    // 加载主题设置
    final themeIndex = _prefs!.getInt(_themeKey) ?? ThemeMode.system.index;
    _themeMode = ThemeMode.values[themeIndex];
    
    // 加载语言设置
    final languageCode = _prefs!.getString(_languageKey) ?? 'zh';
    _locale = Locale(languageCode, languageCode == 'zh' ? 'CN' : 'US');
    
    // 加载通知设置
    _notificationEnabled = _prefs!.getBool(_notificationKey) ?? true;
    
    // 加载每日提醒设置
    _dailyReminderEnabled = _prefs!.getBool('daily_reminder_enabled') ?? true;
    
    // 加载提醒时间
    final reminderHour = _prefs!.getInt('${_reminderTimeKey}_hour') ?? 20;
    final reminderMinute = _prefs!.getInt('${_reminderTimeKey}_minute') ?? 0;
    _reminderTime = TimeOfDay(hour: reminderHour, minute: reminderMinute);
    
    // 加载字体大小设置
    _fontSize = _prefs!.getDouble('font_size') ?? 16.0;
    
    // 加载主题颜色设置
    final colorValue = _prefs!.getInt('primary_color') ?? Colors.blue.toARGB32();
    _primaryColor = Color(colorValue);
    
    // 加载隐私设置
    _privacyMode = _prefs!.getBool(_privacyModeKey) ?? false;
    
    // 加载备份设置
    _autoBackup = _prefs!.getBool(_autoBackupKey) ?? true;
    
    // 加载分析统计设置
    _analyticsEnabled = _prefs!.getBool(_analyticsKey) ?? true;
    
    // 加载应用锁设置
    _appLockEnabled = _prefs!.getBool(_appLockKey) ?? false;
    
    // 加载首次启动标记
    _isFirstLaunch = _prefs!.getBool(_firstLaunchKey) ?? true;
  }

  /// 设置主题模式
  /// [mode] 主题模式
  Future<void> setThemeMode(ThemeMode mode) async {
    if (_themeMode != mode) {
      _themeMode = mode;
      await _prefs?.setInt(_themeKey, mode.index);
      notifyListeners();
    }
  }

  /// 切换到浅色主题
  Future<void> setLightTheme() async {
    await setThemeMode(ThemeMode.light);
  }

  /// 切换到深色主题
  Future<void> setDarkTheme() async {
    await setThemeMode(ThemeMode.dark);
  }

  /// 设置深色模式
  /// [enabled] 是否启用深色模式
  Future<void> setDarkMode(bool enabled) async {
    await setThemeMode(enabled ? ThemeMode.dark : ThemeMode.light);
  }

  /// 切换到系统主题
  Future<void> setSystemTheme() async {
    await setThemeMode(ThemeMode.system);
  }

  /// 切换主题模式
  Future<void> toggleTheme() async {
    switch (_themeMode) {
      case ThemeMode.light:
        await setDarkTheme();
        break;
      case ThemeMode.dark:
        await setSystemTheme();
        break;
      case ThemeMode.system:
        await setLightTheme();
        break;
    }
  }

  /// 设置语言
  /// [locale] 语言区域
  Future<void> setLocale(Locale locale) async {
    if (_locale != locale) {
      _locale = locale;
      await _prefs?.setString(_languageKey, locale.languageCode);
      notifyListeners();
    }
  }

  /// 切换到中文
  Future<void> setChineseLanguage() async {
    await setLocale(const Locale('zh', 'CN'));
  }

  /// 切换到英文
  Future<void> setEnglishLanguage() async {
    await setLocale(const Locale('en', 'US'));
  }

  /// 切换语言
  Future<void> toggleLanguage() async {
    if (_locale.languageCode == 'zh') {
      await setEnglishLanguage();
    } else {
      await setChineseLanguage();
    }
  }

  /// 设置通知开关
  /// [enabled] 是否启用通知
  Future<void> setNotificationEnabled(bool enabled) async {
    if (_notificationEnabled != enabled) {
      _notificationEnabled = enabled;
      await _prefs?.setBool(_notificationKey, enabled);
      notifyListeners();
    }
  }

  /// 切换通知开关
  Future<void> toggleNotification() async {
    await setNotificationEnabled(!_notificationEnabled);
  }

  /// 设置通知开关（别名方法）
  /// [enabled] 是否启用通知
  Future<void> setNotificationsEnabled(bool enabled) async {
    await setNotificationEnabled(enabled);
  }

  /// 设置字体大小
  /// [size] 字体大小
  Future<void> setFontSize(double size) async {
    if (_fontSize != size) {
      _fontSize = size;
      await _prefs?.setDouble('font_size', size);
      notifyListeners();
    }
  }

  /// 设置主题颜色
  /// [color] 主题颜色
  Future<void> setPrimaryColor(Color color) async {
    if (_primaryColor != color) {
      _primaryColor = color;
      await _prefs?.setInt('primary_color', color.value);
      notifyListeners();
    }
  }

  /// 设置提醒时间
  /// [time] 提醒时间
  Future<void> setReminderTime(TimeOfDay time) async {
    if (_reminderTime != time) {
      _reminderTime = time;
      await _prefs?.setInt('${_reminderTimeKey}_hour', time.hour);
      await _prefs?.setInt('${_reminderTimeKey}_minute', time.minute);
      notifyListeners();
    }
  }

  /// 设置隐私模式
  /// [enabled] 是否启用隐私模式
  Future<void> setPrivacyMode(bool enabled) async {
    if (_privacyMode != enabled) {
      _privacyMode = enabled;
      await _prefs?.setBool(_privacyModeKey, enabled);
      notifyListeners();
    }
  }

  /// 切换隐私模式
  Future<void> togglePrivacyMode() async {
    await setPrivacyMode(!_privacyMode);
  }

  /// 设置自动备份
  /// [enabled] 是否启用自动备份
  Future<void> setAutoBackup(bool enabled) async {
    if (_autoBackup != enabled) {
      _autoBackup = enabled;
      await _prefs?.setBool(_autoBackupKey, enabled);
      notifyListeners();
    }
  }

  /// 切换自动备份
  Future<void> toggleAutoBackup() async {
    await setAutoBackup(!_autoBackup);
  }

  /// 设置分析统计
  /// [enabled] 是否启用分析统计
  Future<void> setAnalyticsEnabled(bool enabled) async {
    if (_analyticsEnabled != enabled) {
      _analyticsEnabled = enabled;
      await _prefs?.setBool(_analyticsKey, enabled);
      notifyListeners();
    }
  }

  /// 切换分析统计
  Future<void> toggleAnalytics() async {
    await setAnalyticsEnabled(!_analyticsEnabled);
  }

  /// 设置应用锁
  /// [enabled] 是否启用应用锁
  Future<void> setAppLockEnabled(bool enabled) async {
    if (_appLockEnabled != enabled) {
      _appLockEnabled = enabled;
      await _prefs?.setBool(_appLockKey, enabled);
      notifyListeners();
    }
  }

  /// 切换应用锁
  Future<void> toggleAppLock() async {
    await setAppLockEnabled(!_appLockEnabled);
  }

  /// 设置每日提醒
  /// [enabled] 是否启用每日提醒
  Future<void> setDailyReminderEnabled(bool enabled) async {
    if (_dailyReminderEnabled != enabled) {
      _dailyReminderEnabled = enabled;
      await _prefs?.setBool('daily_reminder_enabled', enabled);
      notifyListeners();
    }
  }

  /// 切换每日提醒
  Future<void> toggleDailyReminder() async {
    await setDailyReminderEnabled(!_dailyReminderEnabled);
  }

  /// 标记应用已不是首次启动
  Future<void> markNotFirstLaunch() async {
    if (_isFirstLaunch) {
      _isFirstLaunch = false;
      await _prefs?.setBool(_firstLaunchKey, false);
      notifyListeners();
    }
  }

  /// 完成引导流程
  Future<void> completeOnboarding() async {
    await markNotFirstLaunch();
  }

  /// 重置为首次启动（用于测试）
  Future<void> resetToFirstLaunch() async {
    _isFirstLaunch = true;
    await _prefs?.setBool(_firstLaunchKey, true);
    notifyListeners();
  }

  /// 获取主题模式的显示名称
  String getThemeModeDisplayName() {
    switch (_themeMode) {
      case ThemeMode.light:
        return isChinese ? '浅色模式' : 'Light Mode';
      case ThemeMode.dark:
        return isChinese ? '深色模式' : 'Dark Mode';
      case ThemeMode.system:
        return isChinese ? '跟随系统' : 'System';
    }
  }

  /// 获取语言的显示名称
  String getLanguageDisplayName() {
    return isChinese ? '中文' : 'English';
  }

  /// 获取提醒时间的显示文本
  String getReminderTimeDisplayText() {
    final hour = _reminderTime.hour.toString().padLeft(2, '0');
    final minute = _reminderTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 重置所有设置为默认值
  Future<void> resetToDefaults() async {
    _themeMode = ThemeMode.system;
    _locale = const Locale('zh', 'CN');
    _notificationEnabled = true;
    _reminderTime = const TimeOfDay(hour: 20, minute: 0);
    _privacyMode = false;
    _autoBackup = true;
    
    // 保存到SharedPreferences
    await Future.wait([
      _prefs?.setInt(_themeKey, _themeMode.index) ?? Future.value(),
      _prefs?.setString(_languageKey, _locale.languageCode) ?? Future.value(),
      _prefs?.setBool(_notificationKey, _notificationEnabled) ?? Future.value(),
      _prefs?.setInt('${_reminderTimeKey}_hour', _reminderTime.hour) ?? Future.value(),
      _prefs?.setInt('${_reminderTimeKey}_minute', _reminderTime.minute) ?? Future.value(),
      _prefs?.setBool(_privacyModeKey, _privacyMode) ?? Future.value(),
      _prefs?.setBool(_autoBackupKey, _autoBackup) ?? Future.value(),
    ]);
    
    notifyListeners();
  }

  /// 导出设置数据
  Map<String, dynamic> exportSettings() {
    return {
      'themeMode': _themeMode.index,
      'language': _locale.languageCode,
      'notificationEnabled': _notificationEnabled,
      'reminderHour': _reminderTime.hour,
      'reminderMinute': _reminderTime.minute,
      'privacyMode': _privacyMode,
      'autoBackup': _autoBackup,
      'isFirstLaunch': _isFirstLaunch,
    };
  }

  /// 导入设置数据
  /// [settings] 设置数据
  Future<void> importSettings(Map<String, dynamic> settings) async {
    try {
      if (settings.containsKey('themeMode')) {
        final themeIndex = settings['themeMode'] as int;
        if (themeIndex >= 0 && themeIndex < ThemeMode.values.length) {
          _themeMode = ThemeMode.values[themeIndex];
        }
      }
      
      if (settings.containsKey('language')) {
        final languageCode = settings['language'] as String;
        _locale = Locale(languageCode, languageCode == 'zh' ? 'CN' : 'US');
      }
      
      if (settings.containsKey('notificationEnabled')) {
        _notificationEnabled = settings['notificationEnabled'] as bool;
      }
      
      if (settings.containsKey('reminderHour') && settings.containsKey('reminderMinute')) {
        final hour = settings['reminderHour'] as int;
        final minute = settings['reminderMinute'] as int;
        if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60) {
          _reminderTime = TimeOfDay(hour: hour, minute: minute);
        }
      }
      
      if (settings.containsKey('privacyMode')) {
        _privacyMode = settings['privacyMode'] as bool;
      }
      
      if (settings.containsKey('autoBackup')) {
        _autoBackup = settings['autoBackup'] as bool;
      }
      
      if (settings.containsKey('isFirstLaunch')) {
        _isFirstLaunch = settings['isFirstLaunch'] as bool;
      }
      
      // 保存所有设置
      await Future.wait([
        _prefs?.setInt(_themeKey, _themeMode.index) ?? Future.value(),
        _prefs?.setString(_languageKey, _locale.languageCode) ?? Future.value(),
        _prefs?.setBool(_notificationKey, _notificationEnabled) ?? Future.value(),
        _prefs?.setInt('${_reminderTimeKey}_hour', _reminderTime.hour) ?? Future.value(),
        _prefs?.setInt('${_reminderTimeKey}_minute', _reminderTime.minute) ?? Future.value(),
        _prefs?.setBool(_privacyModeKey, _privacyMode) ?? Future.value(),
        _prefs?.setBool(_autoBackupKey, _autoBackup) ?? Future.value(),
        _prefs?.setBool(_firstLaunchKey, _isFirstLaunch) ?? Future.value(),
      ]);
      
      notifyListeners();
    } catch (e) {
      if (kDebugMode) {
        print('导入设置失败: $e');
      }
      throw Exception('导入设置失败: $e');
    }
  }

  /// 清除所有设置数据
  Future<void> clearAllSettings() async {
    await _prefs?.clear();
    await _loadSettings(); // 重新加载默认设置
    notifyListeners();
  }
}